import { ref } from 'vue'
import type { Record } from '../types'
import { API_URL } from '../config/apiConfig'
import { addAuthHeader } from './api/apiUtils'
import { authStore } from './auth/store'
import { useRouter } from 'vue-router'

export function useInspectionRecords() {
  const records = ref<Record[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)

  const fetchRecords = async () => {
    try {
      loading.value = true
      error.value = null
      const router = useRouter()
      const response = await fetch(`${API_URL}/demo/compare-result/list`, addAuthHeader(
        {
          credentials: 'include',
          method: 'GET'
        }
      ))
      if (!response.ok) {
        if (response.status === 401 || response.status === 403) {
                  // 清除认证状态
                  authStore.clearAuth()
                  // 重定向到登录页面
                  router.push('/')
                  return
                }
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      records.value = await response.json()
    } catch (err) {
      error.value = '获取检验记录失败，请稍后重试'
      console.error('获取检验记录失败:', err)
    } finally {
      loading.value = false
    }
  }

  return {
    records,
    loading,
    error,
    fetchRecords
  }
}
